package pro4;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/Ans4/UpdateCartServlet")
public class UpdateCartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        List<CartItem> cartItems = (List<CartItem>) session.getAttribute("cartItems");

        if (cartItems == null) {
            cartItems = new ArrayList<>();
        }

        String action = request.getParameter("action");

        if ("add".equals(action)) {
            // 添加商品（来自 AddToCartServlet）
            String id = request.getParameter("id");
            String name = request.getParameter("name");
            double price = Double.parseDouble(request.getParameter("price"));
            int stock = Integer.parseInt(request.getParameter("stock"));
            String imageUrl = request.getParameter("imageUrl");

            cartItems.add(new CartItem(new Product(id, name, price, stock, imageUrl), 1));

        } else if ("increase".equals(action)) {
            // 增加数量
            int index = Integer.parseInt(request.getParameter("index"));
            if (index >= 0 && index < cartItems.size()) {
                CartItem item = cartItems.get(index);
                if (item.getQuantity() < item.getProduct().getStock()) {
                    item.setQuantity(item.getQuantity() + 1);
                }
            }

        } else if ("decrease".equals(action)) {
            // 减少数量
            int index = Integer.parseInt(request.getParameter("index"));
            if (index >= 0 && index < cartItems.size()) {
                CartItem item = cartItems.get(index);
                if (item.getQuantity() > 1) {
                    item.setQuantity(item.getQuantity() - 1);
                } else {
                    cartItems.remove(index); // 数量为0时直接删除
                }
            }

        } else if ("remove".equals(action)) {
            // 删除商品
            int index = Integer.parseInt(request.getParameter("index"));
            if (index >= 0 && index < cartItems.size()) {
                cartItems.remove(index);
            }
        }

        session.setAttribute("cartItems", cartItems);
        response.sendRedirect("cart.jsp");
    }
}
